package com.demo.springbootdemonettywebsocket.client;

import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.nio.channels.NotYetConnectedException;
import java.util.Timer;
import java.util.TimerTask;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

/**
 * @author peter
 * @date 2022/5/30 上午11:52
 */
@Slf4j
public class MyWebSocketClient extends WebSocketClient {

    // 定时器
    private Timer timer = new Timer();
    // 心跳检测
    private volatile boolean isPong = true;

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info(">>>>>>>>>>>websocket open");

        // 模拟心跳
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (isPong) {
                    log.info("心跳发送");
                    if (MyWebSocketClient.super.isOpen()) {
                        MyWebSocketClient.super.send("ping");
                        isPong = false;
                    }
                } else {
                    log.info("心跳失败");
                    if (MyWebSocketClient.super.isOpen()) {
                        MyWebSocketClient.super.close();
                    }
                }

            }
        }, 2000 , 2*1000);
    }

    @Override
    public void onMessage(String s) {
        log.info(">>>>>>>>>> websocket message {}", s);
        if (s.toLowerCase().equals("pong")) {
            this.isPong = true;
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info(">>>>>>>>>>>websocket close");
        timer.cancel();
    }

    @Override
    public void onError(Exception e) {
        log.error(">>>>>>>>>websocket error {}",e);
    }

    @Override
    public void send(String text) throws NotYetConnectedException {
        log.info("send {}" , text);
        super.send(text);
    }
}
